package class08_前缀树不基于比较的排序排序的稳定性.test;

import java.util.Arrays;

/**
 * 计数排序
 */
public class Code03_CountSort {
    public static void countSort(int[] arr){
        if(arr == null || arr.length < 2){
            return;
        }
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            max = Math.max(arr[i], max);
        }
        int[] bucket = new int[max + 1];
        for (int i = 0; i < arr.length; i++) {
            bucket[arr[i]]++;
        }
        int index = 0;
        for (int i = 0; i < bucket.length; i++) {
            while (bucket[i] > 0){
                bucket[i]--;
                arr[index++] = i;
            }
        }
    }

    public static void main(String[] args) {
        int testTimes = 50000;
        int maxValue = 100;
        int maxSize = 100;
        boolean succeed = true;
        for (int i = 0; i < testTimes; i++) {
            int[] arr = generateRandomArray(maxSize, maxValue);
            int[] arr2 = copyArray(arr);
            countSort(arr);
            comparator(arr2);
            if(!isEqual(arr, arr2)){
                succeed = false;
                printArray(arr);
                printArray(arr2);
            }
        }
        System.out.println(succeed?"Good!!":"Fuck!!!");
    }

    private static void printArray(int[] arr) {
        if(arr == null){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    private static boolean isEqual(int[] arr, int[] arr2) {
        if(arr == null && arr2 != null){
            return false;
        }
        if(arr != null && arr2 == null){
            return false;
        }
        if(arr.length != arr2.length){
            return false;
        }
        if(arr == null && arr2 == null){
            return true;
        }
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] != arr2[i]){
                return false;
            }
        }
        return true;
    }

    private static void comparator(int[] arr2) {
        Arrays.sort(arr2);
    }

    private static int[] copyArray(int[] arr) {
        if(arr == null) {
            return new int[0];
        }
        int[] ans = new int[arr.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i] = arr[i];
        }
        return ans;
    }

    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int size = (int)(Math.random() * maxSize + 1);
        int[] help = new int[size];
        for (int i = 0; i < help.length; i++) {
            help[i] = (int)(Math.random() * maxValue + 1);
        }
        return help;
    }
}
